/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MaestroMarcasVehiculos.java
 *
 * Created on 05-jul-2012, 23:42:03
 */
package com.camachosanchez.gui;

import com.camachosanchez.bean.MarcasVehiculo;
import com.camachosanchez.controler.jdbc.MarcasVehiculosJdbcControler;
import com.camachosanchez.controler.jpa.MarcasVehiculoJpaController;
import com.camachosanchez.gui.table.ModeloTablaMarcasVehiculos;
import com.camachosanchez.gui.table.RenderizadorTabla;
import com.camachosanchez.gui.table.TableSorter;
import com.camachosanchez.util.GUIUtil;
import com.camachosanchez.util.JPAUtil;
import java.util.List;
import javax.persistence.Query;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import javax.swing.event.InternalFrameEvent;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import net.coderazzi.filters.gui.TableFilterHeader;

/**
 *
 * @author Rolando
 */
public class MaestroMarcasVehiculos extends javax.swing.JInternalFrame {

    private ModeloTablaMarcasVehiculos modelo;
    private TableFilterHeader filterHeader;

    /** Creates new form MaestroMarcasVehiculos */
    public MaestroMarcasVehiculos() {
        initComponents();
        modelo = new ModeloTablaMarcasVehiculos();
        TableSorter tableSorter = new TableSorter(modelo, tablaMarcas.getTableHeader());
        tablaMarcas.setModel(tableSorter);
        filterHeader = new TableFilterHeader();
        filterHeader.setTable(tablaMarcas);
        RenderizadorTabla render = new RenderizadorTabla();
        tablaMarcas.setDefaultRenderer(String.class, render);
        this.llenarMarcas();
        this.setSize(400, 480);
        tablaMarcas.getTableHeader().setReorderingAllowed(false);
        setFrameIcon(new ImageIcon(getClass().getResource("/com/camachosanchez/recursos/table.png")));
        GUIUtil.fondoBarraHerramientas(jToolBar1);
        this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        this.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter() {

            @Override
            public void internalFrameClosing(InternalFrameEvent e) {
                cerrar();
            }
        });
    }

    private void cerrar() {
        GUIUtil.maximizarTodasLasVentanas(this);
    }

    private void llenarMarcas() {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                modelo.limpiar();
                setAnchoColumnas();
                try {
                    Query q = JPAUtil.getEntityManagerFactory().createEntityManager().createNamedQuery("MarcasVehiculo.findByEstado");
                    q.setParameter("estado", true);
                    List<MarcasVehiculo> marcas = q.getResultList();
                    for (MarcasVehiculo marcarVehiculo : marcas) {
                        modelo.agregarMarca(marcarVehiculo);
                    }
                    GUIUtil.SetAnchoColumnas(tablaMarcas);
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(Principal.getInstance(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

    }

    private void setAnchoColumnas() {
        int anchoColumna;
        TableColumnModel modeloColumna = tablaMarcas.getColumnModel();
        TableColumn columnaTabla;
        for (int i = 0; i < tablaMarcas.getColumnCount(); i++) {
            columnaTabla = modeloColumna.getColumn(i);
            switch (i) {
                case 0:
                    anchoColumna = 25;
                    columnaTabla.setMinWidth(anchoColumna);
                    columnaTabla.setMaxWidth(anchoColumna);
                    columnaTabla.setPreferredWidth(anchoColumna);
                    break;
                case 1:
                    anchoColumna = 0;
                    columnaTabla.setMinWidth(anchoColumna);
                    columnaTabla.setMaxWidth(anchoColumna);
                    columnaTabla.setPreferredWidth(anchoColumna);
                    break;
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        jPanel2 = new javax.swing.JPanel();
        btnNuevo = new javax.swing.JButton();
        btnModificar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaMarcas = new javax.swing.JTable();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle(".:: Marcas de Vehículos ::.");

        jToolBar1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 4, 4));

        btnNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/24_new.png"))); // NOI18N
        btnNuevo.setToolTipText("Nuevo");
        btnNuevo.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnNuevo.setFocusable(false);
        btnNuevo.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnNuevo.setMaximumSize(new java.awt.Dimension(22, 22));
        btnNuevo.setMinimumSize(new java.awt.Dimension(22, 22));
        btnNuevo.setPreferredSize(new java.awt.Dimension(22, 22));
        btnNuevo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });
        jPanel2.add(btnNuevo);

        btnModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/24_edit.png"))); // NOI18N
        btnModificar.setToolTipText("Modificar");
        btnModificar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnModificar.setFocusable(false);
        btnModificar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnModificar.setMaximumSize(new java.awt.Dimension(22, 22));
        btnModificar.setMinimumSize(new java.awt.Dimension(22, 22));
        btnModificar.setPreferredSize(new java.awt.Dimension(22, 22));
        btnModificar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModificarActionPerformed(evt);
            }
        });
        jPanel2.add(btnModificar);

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/24_delete.png"))); // NOI18N
        btnEliminar.setToolTipText("Eliminar");
        btnEliminar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnEliminar.setFocusable(false);
        btnEliminar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnEliminar.setMaximumSize(new java.awt.Dimension(22, 22));
        btnEliminar.setMinimumSize(new java.awt.Dimension(22, 22));
        btnEliminar.setPreferredSize(new java.awt.Dimension(22, 22));
        btnEliminar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });
        jPanel2.add(btnEliminar);

        jToolBar1.add(jPanel2);

        getContentPane().add(jToolBar1, java.awt.BorderLayout.PAGE_START);

        jPanel1.setLayout(new java.awt.BorderLayout());

        tablaMarcas.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(156, 161, 165)));
        tablaMarcas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tablaMarcas.setRowHeight(22);
        tablaMarcas.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(tablaMarcas);

        jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
// TODO add your handling code here:
    String marcaVehiculo = JOptionPane.showInputDialog(null, "Nombre de la marca : ", ".:: Marca de Vehículo ::.", JOptionPane.QUESTION_MESSAGE);
    if (marcaVehiculo != null) {
        if (marcaVehiculo.length() < 45) {
            MarcasVehiculoJpaController controller = new MarcasVehiculoJpaController(null);
            MarcasVehiculo marca = new MarcasVehiculo();
            marca.setNombre(marcaVehiculo);
            marca.setEstado(true);
            controller.create(marca);
            llenarMarcas();
        } else {
            JOptionPane.showMessageDialog(this, "El nombre de la marca debe tener menos caracteres.", "Datos incorrectos", JOptionPane.WARNING_MESSAGE);
        }
    }
}//GEN-LAST:event_btnNuevoActionPerformed

private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarActionPerformed
// TODO add your handling code here:
    int fila = tablaMarcas.getSelectedRow();
    if (fila > -1) {
        int id = Integer.parseInt(tablaMarcas.getValueAt(fila, 1).toString());
        MarcasVehiculoJpaController controller = new MarcasVehiculoJpaController(null);
        MarcasVehiculo marca = controller.findMarcasVehiculo(id);
        if (marca != null) {
            String marcaNeumatico = JOptionPane.showInputDialog(null, marca.getNombre() + " a : ", "¿Desea Actualizar?", JOptionPane.QUESTION_MESSAGE);
            if (marcaNeumatico != null) {
                try {
                    marca.setNombre(marcaNeumatico);
                    controller.edit(marca);
                    llenarMarcas();
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(Principal.getInstance(), ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    } else {
        JOptionPane.showMessageDialog(this, "Debe seleccionar una marca.", "Advertencia", JOptionPane.WARNING_MESSAGE);
    }
}//GEN-LAST:event_btnModificarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        // TODO add your handling code here:
        int fila = tablaMarcas.getSelectedRow();
        if (fila > -1) {
            if (JOptionPane.showConfirmDialog(null, "¿Está seguro que desea eliminar la marca seleccionada?", "Confirmación", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                int id = Integer.parseInt(tablaMarcas.getValueAt(fila, 1).toString());
                MarcasVehiculosJdbcControler daoJdbc = new MarcasVehiculosJdbcControler();
                byte estado = daoJdbc.eliminarMarca(id);
                if (estado == 1) {
                    JOptionPane.showMessageDialog(this, "La marca se encuentra relacionado con otros registros, no puede ser eliminada.", "Error en la eliminación", JOptionPane.ERROR_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(this, "La marca se ha eliminado de forma segura.", "Operación finalizada", JOptionPane.INFORMATION_MESSAGE);
                    modelo.borrarAccion(fila);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "Debe seleccionar una marca.", "Advertencia", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnEliminarActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnModificar;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTable tablaMarcas;
    // End of variables declaration//GEN-END:variables
}
